from jinja2 import Template
from utils.path_manager import path_manager

import os
import yaml
import re


class AutoGeneratePageFile():
    template_str = '''from utils.base_page import BasePage

class {{ filename }}(BasePage):

    def __init__(self):
        super().__init__()
        {% for item in data %}
        self.{{ item }} = self.get_locator('{{ item }}')
        {%- endfor -%}
'''

    def generate_page_file(self, overwrite=False):

        """
        自动根据YAML定位信息文件生成Page文件
        :param overwrite: 如果Page文件已存在,overwrite为True会重新生成对应Page文件
        :return:
        """

        for filename in os.listdir(path_manager.ELEMENT_PATH):

            if filename.endswith('yaml'):

                file_path = os.path.join(path_manager.ELEMENT_PATH, filename)

                with open(file_path, encoding='utf-8') as f:
                    data = yaml.safe_load(f)

                    template = Template(self.template_str)
                    result = template.render(filename=filename.replace('.yaml', ''), data=list(data.keys()))

                filename = self.name_convert_to_snake(filename.replace('yaml', 'py'))
                pypath = ''.join([config.PAGE_PATH, os.sep, filename])
                file_exists = os.path.exists(pypath)

                if not file_exists or (file_exists and overwrite):
                    with open(pypath, "w") as f:
                        f.write(result)
                    print("%s generate success" % filename)

    def name_convert_to_snake(self, name: str) -> str:
        """驼峰转下划线"""
        if re.search(r'[^_][A-Z]', name):
            name = re.sub(r'([^_])([A-Z][a-z]+)', r'\1_\2', name)
            return self.name_convert_to_snake(name)
        return name.lower()

    def name_convert_to_camel(self, name: str) -> str:
        """下划线转驼峰"""
        contents = re.findall('_[a-z]+', name)
        for content in set(contents):
            name = name.replace(content, content[1:].title())
        return name


if __name__ == '__main__':
    AutoGeneratePageFile().generate_page_file()
